#!/bin/sh
export H="$PWD"
. ./config

if [ ! -r "$H"/config ]; then
    printf -- "couldn't read configuration file: %s\n" "$H/config"
    printf -- "copy %s to %s and edit appropriately\n" "$K/config.stage0" "$H/config"
    exit 1
fi

# ./build-stage 1 is only for building a fresh stage1 from WITHIN sabotage. To
# build from out of sabotage, you need to ./build-stage 0, then build stage1
# with butch from within the built system.
STAGE="$1"
if [ ! "$STAGE" ]
then
    printf -- "Please specify a stage to build.\n"
    exit 1
fi
printf -- "Building stage %d\n" "$STAGE"

# enable verbose printing, abort on error
set -e -x

. "$H"/utils/sabotage-prereqs
. "$H"/utils/utils
. "$H"/utils/setup-rootfs
if [ "$STAGE" = "0" ] ; then
	CC_SAVE="$CC"
	. "$H"/utils/build-butch
	CC="$CC_SAVE"
fi

# update-buildroot - copy to sources
cp -r "$H"/pkg "$S"/
cp -r "$H"/KEEP "$S"/

# on ARM, gcc 3.4.6 is not sufficient to build for EABI
[ "$A" = "arm" ] && cat << EOF > "$S"/pkg/stage0_gcc
[deps]
gcc424
EOF

if [ "$STAGE" = "0" ] ; then
	# build stage0
	CONFIG="$H/config" BUTCHDB="$R"/var/lib/butch.db "$R"/bin/butch install stage0
else
	# build stage1
	butch install stage1

	# build butch
	butch install butch

	# and finalize the chroot
	"$H"/utils/finish
fi

